package com.longe.nio.buffer;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.stream.Stream;

public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws Exception {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(9999);
        //绑定端口
        serverSocket.bind(inetSocketAddress);

        //定义buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        //模拟从客户端接收的字节数为8
        int messageSize = 8;

        while (true) {
            long readSize = 0;
            while (readSize < messageSize) {
                long read = socketChannel.read(byteBuffers);
                readSize += read;
                System.err.println("readSize = " + readSize);
                Stream.of(byteBuffers)
                        .map(byteBuffer -> "position = " + byteBuffer.position() + ", limit = " + byteBuffer.limit())
                        .forEach(System.err::println);
            }

            //翻转
            Stream.of(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

            long writeSize = 0;
            while (writeSize < messageSize) {
                long write = socketChannel.write(byteBuffers);
                writeSize += write;
                System.err.println("writeSize = " + writeSize);
                System.out.println("readSize = " + readSize + "writeSize = " + writeSize);
            }

            //复位
            Stream.of(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
        }
    }
}
